'use strict';

/**
 * @param {Egg.Application} app - egg application
 */

module.exports = app => {
  const { router, model, controller } = app;

  router.get('/', controller.home.index);
  router.get('/index', controller.home.index);
  router.get('/main', controller.home.main);
  router.get('/login', controller.system.admin.login);
  router.get('/init', controller.system.admin.init);
  router.get('/getCode', controller.home.getCode);
  router.post('/userLogin', controller.system.admin.userLogin);
  router.get('/userLogout', controller.system.admin.userLogout);
  router.post('/userRegister', controller.system.admin.userRegister);
  router.get('/error/:id', controller.system.admin.error);
  router.get('/profile', controller.home.profile_page);
  router.put('/profile/:id', controller.home.profile);
  router.get('/changePwd', controller.home.changePwd_page);
  router.put('/changePwd/:id', controller.home.changePwd);
  router.post('/api/home/uploadFile', controller.api.home.uploadFile); // 上传文件

  model.Router.findAll({ where: { status: 1 }, raw: true }).then(result => {
  //  router.get('/main', controller.home.main);

    result.forEach(json => {
      const controller_obj = json.controller_name.toLowerCase().indexOf('controller.') === 0 ? json.controller_name.substr(11) : json.controller_name;
      let action_name = json.action_name.toLowerCase();
      action_name = action_name === 'del' ? 'delete' : action_name;
      if (controller_obj) {
        try {
          if (json.middleware_name) {
            const middlewares = json.middleware_name.split(','); // 多个中间件用逗号分隔
            router[action_name](json.path, ...middlewares, controller_obj);
          } else {
            router[action_name](json.path, controller_obj);
          }
        } catch (error) {
          console.log('controller err:' + controller_obj);
        }
      } else {
        console.log('controller err:' + json.controller_name);
      }
    });
  }).catch(err => {
    app.dumpError(err);
  });
};

